/*
 * Copyright © 2009 Perseus Project - Tufts University <http://www.perseus.tufts.edu>
 *
 * This file is part of UniCollatorPerseus.
 *
 * OcroPerseus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * OcroPerseus is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with OcroPerseus.  If not, see <http://www.gnu.org/licenses/>.
 */

package eu.himeros.ocr.image;

import eu.himeros.util.IoManager;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.InputStreamReader;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

/**
 *
 * @author Federico Boschetti <federico.boschetti.73@gmail.com>
 */
public class BoxPainter {
    BufferedReader pbmBr=null;
    BufferedReader boxBr=null;
    BufferedWriter bw=null;
    int w=0;
    int h=0;
    String fileName=null;    
    BufferedImage buffImg=null;
    Image img=null;
    Toolkit tk=null;
    MediaTracker mt=null;
    Graphics2D g2d=null;    
    Runtime runtime=null;
    Process proc=null;
    int[][] imgMtx=null;
    String flag="false";

    /**
     *
     */
    public BoxPainter(){}

    /**
     *
     * @param fileName
     * @param flag
     */
    public BoxPainter(String fileName,String flag){
        this.fileName=fileName;
        this.flag=flag;
        if(flag.equals("true")){
            copyImg(false);
        }else{
            copyImg(true);
        }
        init();
        fillMatrix();
        paintBox();
        close();
    }

    /**
     *
     * @param reverse
     */
    public void copyImg(boolean reverse){
            runtime=Runtime.getRuntime();
            try{
                if(!reverse){
                    proc=runtime.exec("convert "+fileName+".png "+fileName+".tif");proc.waitFor();
                }else{
                    proc=runtime.exec("cp "+fileName+".png "+fileName+"_.png");proc.waitFor();      
                }
            }catch(Exception ex){ex.printStackTrace();}
    }

    /**
     *
     */
    private void init(){
        try{
            proc=runtime.exec("convert "+fileName+".tif "+fileName+".png");proc.waitFor();
            tk=Toolkit.getDefaultToolkit();
            if(flag.equals("true")){
                img=tk.getImage(fileName+".png");
            }else{
                img=tk.getImage(fileName+"_.png");
            }
            img=(new ImageIcon(img)).getImage();         
            buffImg=new BufferedImage(img.getWidth(null),img.getHeight(null),BufferedImage.TYPE_INT_RGB);
            g2d=buffImg.createGraphics();
            g2d.drawImage(img, 0, 0,null);
            if(flag.equals("true")){
                g2d.setColor(Color.RED);
            }else{
                g2d.setColor(Color.BLUE);
            }
            boxBr=IoManager.getReader(fileName+".box");
            bw=IoManager.getWriter(fileName+".gbx");
            runtime=Runtime.getRuntime();
            proc=runtime.exec("convert "+fileName+".png "+fileName+".pbm");proc.waitFor();
            proc=runtime.exec("pnmtoplainpnm "+fileName+".pbm");
            pbmBr=new BufferedReader(new InputStreamReader(proc.getInputStream()));
        }catch(Exception e){e.printStackTrace();}
    }

    /**
     *
     */
    private void fillMatrix(){
        try{
            System.out.println(pbmBr.readLine());
            String[] dims=pbmBr.readLine().split(" ");
            System.out.println(dims[0]+" "+dims[1]);
            w=Integer.parseInt(dims[0]);
            h=Integer.parseInt(dims[1]);
            imgMtx=new int[w][h];
            int ci=-1;
            int i=0;
            int j=h-1;
            while((ci=pbmBr.read())!=-1){
                char c=(char)ci;
                if(c=='0'||c=='1'){
                    imgMtx[i][j]=c;
                    i++;
                    if(i==w){
                        i=0;
                        j--;
                    }                    
                }
            }
            proc.waitFor();
        }catch(Exception e){e.printStackTrace();}
    }

    /**
     *
     */
    private void paintBox(){
        String line=null;
        String[] items=null;
        int x1=0;
        int y1=0;
        int x2=0;
        int y2=0;
        try{
            while((line=boxBr.readLine())!=null){
                items=line.split(" ");
                try{
                    x1=Integer.parseInt(items[1]);
                    y1=Integer.parseInt(items[4]);
                    x2=Integer.parseInt(items[3]);
                    y2=Integer.parseInt(items[2]);
                }catch(Exception ex){continue;}
                if(flag.equals("true")){
                    g2d.setColor(Color.RED);
                }else{
                    g2d.setColor(Color.BLUE);
                }
                g2d.drawRect(x1,h-y1,x2-x1,y1-y2);
                for(int i=y1;i>y2;i--){
                    for(int j=x1;j<x2;j++){
                        if(imgMtx[j][i]==48){
                            bw.write(".");
                        }else{
                            bw.write("\u2589");
                        }
                    }
                    bw.newLine();
                }
                bw.write("#\n"+line);bw.newLine();
                bw.newLine();bw.newLine();
            }
        }catch(Exception e){e.printStackTrace();}
    }

    /**
     *
     */
    private void close(){
        try{
            bw.flush();bw.close();
            ImageIO.write(buffImg,"png",new File(fileName+".png"));
        }catch(Exception e){e.printStackTrace();}
    }

    /**
     *
     * @param args
     */
    public static void main(String[] args){
        BoxPainter bp=new BoxPainter(args[0],args[1]);
    }
}
